package com.itec.learn.java.design.observer.event;

import java.util.HashSet;
import java.util.Set;

/**
 * @author chenyiqun
 */
public class StateHolder {
    private final Set<StateListener> listeners = new HashSet<StateListener>();
    private int state;

    public int getState() {
        return state;
    }

    public void setState(int state) {
        int oldState = this.state;
        this.state = state;
        if (oldState != state) {
            broadcast(new StateEvent(oldState, state));
        }
    }

    public void addStateListener(StateListener listener) {
        listeners.add(listener);
    }

    public void removeStateListener(StateListener listener) {
        listeners.remove(listener);
    }

    private void broadcast(StateEvent stateEvent) {
        for (StateListener listener : listeners) {
            listener.stateChanged(stateEvent);
        }
    }
}
